<?php

namespace app\admin\logic;

use app\api\logic\FeiShuMessageLogic;
use think\facade\Request;
use app\admin\model\AdminModel;
use app\admin\model\SmsRecordModel;
use app\api\controller\SendMessage;
use think\Model;
use app\admin\logic\BasicLogic;
use app\admin\validate\AdminLogin;
use think\facade\Validate;
use Firebase\JWT\JWT;
use think\facade\Cache;
use app\data\cache\CacheToken;
use think\facade\Db;
use app\data\util\HttpUtil;


class AdminLogic extends BasicLogic
{
    //注入所需模型以及操作类
    protected $adminModel     = null;
    protected $smsRecordModel = null;
    protected $adminLogin     = null;
    public function __construct(
        AdminModel     $adminModel,
        SmsRecordModel $smsRecordModel,
        AdminLogin     $adminLogin
    )
    {
        $this->adminModel     = $adminModel;
        $this->smsRecordModel = $smsRecordModel;
        $this->adminLogin     = $adminLogin;
    }

    /**
     * @desc 登录发送短信验证码
     * @author  xx
     * @date 2024-02-29
     */
    public function  sendSms($data=[]){
        $request = Request::instance();
        if ($request->isPost()){
            //获取员工的手机号;
            $docTel  = $data['tel']??'';
            $smsType = $data['smsType']??'';
            $isTel   = isMobiles($docTel);
            if($isTel == false){
                return $this->jsonMessage(201, false, '手机号格式有误', null);
            }

            if(!$smsType){
                return $this->jsonMessage(201, false, '短信类型不能为空', null);
            }

            $is_exist = self::getAccount($docTel);
            if($is_exist){
                return $this->jsonMessage(201, false, $is_exist, null);
            }
            $res = (new SendMessage())->sendCode(['tel'=>$docTel,'smsType'=>$smsType]);
            if(isset($res['res']['Code']) && isset($res['data']['code']) && $res['res']['Code']=='OK'){
                self::addSmsRecord($res['data']);
                return $this->jsonMessage(200, true, '获取成功', $res['data']['code']);
            }else{
                htmlLog(['tel'=>$docTel,'response'=>$res],OPERATE_LOG . date('Ym') . '/sendSmsInfo/' . date('Ymd') . '.txt');
                return $this->jsonMessage(201, false, '获取失败', null);
            }
        }

    }


    /**
     * @desc 手机号登录
     * @author xx
     * @date 2024-03-01
     */
    public function telLogin($data=[]){
        $data['smsType'] = '1';
        //验证器参数验证
        $res = $this->adminLogin->check($data);

        if(!$res) return $this->jsonMessage(201, false, $this->adminLogin->getError(), null);
        //验证码是否有效验证
        $is_right =  self::checkCode($data);

        if($is_right) return $this->jsonMessage(201, false, $is_right, null);
        //查询该手机号用户是否存在;
        $is_exist = self::getAccount($data['tel']);
        if($is_exist) return $this->jsonMessage(201, false, $is_exist, null);
        //没有问题把TOEKN传过去登录成功
        $res = self::createToken($data['tel']);
        if(!is_array($res))  return $this->jsonMessage(201, false, $res, null);
        //更新登录时间;
        $this->adminModel->where(['id'=>$res['id']])->update(['update_time'=>date("Y-m-d H:i:s", time())]);
        //更新验证码状态;
        //$this->smsRecordModel->where(['tel'=>$data['tel'],'code'=>$data['checkCode']])->update(['is_used'=>'on']);
        return $this->jsonMessage(200, true, '登录成功', $res);
    }


    /**
     * @desc 扫码登录
     * @author xx
     * @date 2024-03-01
     */
    public function codeLogin($data=[]){
        try{
            $code  = $data['code'] ??'';
            htmlLog(['code'=>$code],OPERATE_LOG . date('Ym') . '/codeLogin/' . date('Ymd') . '.txt');
            if(!$code)  return $this->jsonMessage(201, false, 'code不能为空!', null);
            $access_token = self::getAccessToken($code);
            $tel          = self::getUserInfo($access_token);
            //没有问题把TOEKN传过去登录成功
            $res = self::createToken($tel);
            if(!is_array($res))  return $this->jsonMessage(201, false, $res, null);
            //更新登录时间;
            $this->adminModel->where(['id'=>$res['id']])->update(['update_time'=>date("Y-m-d H:i:s", time())]);
            return $this->jsonMessage(200, true, '登录成功', $res);
        }catch (\Exception $e){
            return error('登录失败:' . $e->getMessage());
        }

    }





    /**
     * @desc 手机号登出
     * @author xx
     * @date 2024-03-05
     */
    public function loginOut(){
        return $this->jsonMessage(200, true, '登出成功', null);
    }





    /**
     * @desc 存储验证码信息
     * @author xx
     * @date 2024-02-29
     *
     */
    public function addSmsRecord($param){
        $data['tel']          = $param['tel'];
        $data['sms_type']     = $param['sms_type'];
        $data['code']         = $param['code'];
        $data['message']      = $param['message'];
        $data['created_time'] = date('Y-m-d H:i:s',time());
        $data['expire_time']  = date('Y-m-d H:i:s',strtotime('+7 days'));
        $this->smsRecordModel->insert($data);
    }


    /**
     * 检验验证码
     * @param $value
     * @param $rule
     * @param $data
     * @return bool|string
     */
    protected function checkCode($data){
        $map["sms_type"]  =   $data['smsType'];
        $map["tel"]       =   $data['tel'];
        $map["code"]      =   $data['checkCode'];
        $obj              =   $this->smsRecordModel->where($map)->order("created_time desc")->find();
        //是否使用过验证码
        if (!isset($obj['code'])) {
            return '验证码不正确';
        }else{
            if($obj['is_used'] == 'on'){
                return '验证码已经使用过了';
            }
            if($obj['expire_time'] < date('Y-m-d H:i:s',time())){
                return '验证码已过期';
            }
            return '';
        }
    }

    /**
     * @desc 查看员工是否存在
     * @author xx
     * @date 2024-03-01
     *
     */
    private function getAccount($tel=''){
        $res = $this->adminModel->where(['phone'=>$tel])->find();
        $res = objectToArray($res);
        if($res){
            return isset($res['status']) && $res['status']==0 ? '该员工账号被禁用' : '';
        }else{
            return '该员工还未授权';
        }
    }


    /**
     * @DESC 生成登录token
     * @author  xx
     * @date 2024-03-01
     */
    private function createToken($tel){
        $info = $this->adminModel->where(['phone'=>$tel])->find();
        $info = objectToArray($info);
        //获取当前登录员工的分组ID;
        $groupId = Db::name('system_group_admin')->where(['admin_id'=>$info["id"]])->value('group_id');
        if(!$groupId)  return '请给该员工配置角色分组';
        //是否管理员ID;
        $admin_group_id = $info['group_ids']??'';
        //生成token;
        $newToken = tokens();
        $token = [
            "id"               => $info["id"],
            "tel"              => $info["phone"],
            "username"         => $info["username"],
            "nickname"         => $info["nickname"],
            "avatar"           => $info["head_image"],
            "email"            => $info["email"],
            "last_login_time"  => $info["update_time"],
            "groupId"          => $groupId,
            "admin_group_id"   => $admin_group_id,
            "token"            => $newToken
        ];
        $jwt = JWT::encode($token, env('JWT_JWT_SALT'));
        //缓存客户端token;
        CacheToken::setAdminPcData($tel, $newToken);
        //返回登录信息;
        return [
           'id'              =>$info['id'],
           'phone'           =>$info['phone'],
           'username'        =>$info['username'],
           'nickname'        =>$info['nickname'],
           'avatar'          =>$info['head_image'],
           'email'           =>$info['email'],
           'last_login_time' =>$info['update_time'],
           'groupId'         =>$groupId,
           'token'           =>$jwt,
        ];
    }



    /**
     * @desc 同步到待退款列表
     * @author xx
     * @date 2025-03-01
     */
    public function RegistrationRefund($data=[]){
        $SpecificReasons = $data['SpecificReasons'] ?? "";
        if(empty($SpecificReasons)){
            return $this->jsonMessage(201, true, '请添加退款意向');
        }
        $shop_name = $data['shop_name'] ?? "";
        $shop_id = 0;
        switch ($shop_name) {
            case 'SheCurve':
                $shop_id = 17;
                break;
            case 'woobilly':
                $shop_id = 21;
                break;
            case 'LilyLove':
                $shop_id = 18;
                break;
            case 'kisslove':
                $shop_id = 22;
                break;
            default:
                $shop_id = 0;
        }
        
        // if($shop_name !== 'SheCurve'){
        //     $slug = $data['slug'] ?? "";
        //     //查询是否是SheCurve店铺
        //     if(!empty($slug)){
        //         $email        = Config('Logisticskey.apireamaze.email');
        //         $token        = Config('Logisticskey.apireamaze.token');
        //         $url = 'https://SheCurve.reamaze.io/api/v1/conversations/'.$slug;
        //         $return = HttpUtil::getUrlReamaze($url, ['email' => $email, 'token' => $token]);
        //         if(isset($return['slug']) && $return['slug'] == $slug){
        //             $shop_id = 17;
        //         }
        //     }
        // }else{
        //     $shop_id = 17;
        // }
        if($shop_id == 0){
            return $this->jsonMessage(201, true, '请添加店铺');
        }
        if($SpecificReasons == '产品问题反馈' || $SpecificReasons == '补发'){
            $currency = $data['currency'] ?? "";
            $refund_payment = $data['amount'] ?? 0;
        }else{
            $currency = $data['currency'] ?? "";;
            if(empty($currency)){
                return $this->jsonMessage(201, true, '请添加币种');
            }
            $refund_payment = $data['amount'] ?? 0;
            if($refund_payment <= 0){
                return $this->jsonMessage(201, true, '请添加退款金额');
            }
        }
        $order_number = $data['order_number'] ?? "";
        //新增条件
        $ReasonForRefund = $data['ReasonForRefund'] ?? "";
        $ProductSku = $data['ProductSku'] ?? "";
        $Supplementary = $data['Supplementary'] ?? "";
        $valuesome = [21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44];
        $valuesome2 = [37,43,48];
        if(!empty($ReasonForRefund)){
            if(in_array($ReasonForRefund,$valuesome2)){
                 //其他产品质量问题
                if(empty($Supplementary)){
                    return $this->jsonMessage(201, true, '请先添加补充描述');
                }
            }
            if(in_array($ReasonForRefund,$valuesome)){
                //其他产品质量问题
                if(empty($ProductSku)){
                    return $this->jsonMessage(201, true, '请先添加SKU');
                }
            }
        }
        $skus = "";
        if(!empty($ProductSku)){
            $order_info = db::name('order_info')->field('sku')->where('id',"in",$ProductSku)->select()->toarray();
            $skus = array_column($order_info,'sku');
            $skus = implode(',',$skus);
            $skus = $skus ?? "";

            $ProductSku = implode(',',$ProductSku);
        }

        //同步到待退款列表
        $order_info      =    Db::name('order')->field('id,order_id,total_price')->where(['shop_id'=>$shop_id,'order_number'=>$order_number])->find();
        $order_id        =    $order_info['order_id']??'';
        if(!$order_id)  return $this->jsonMessage(201, true, '订单数据不匹配');

        //有Dispute标签的不同步
        $tags = Db::name('order_achievement')->where('order_id',$order_id)->value('tags');
        if(isset($tags) && strpos($tags,'dispute') !== false){
            // return $this->jsonMessage(201, true, '订单有dispute标签，不能同步到待退款列表');
        }

        //查看当前$order_id是否退过款;
        $refund_id       = Db::name('order_transactions')
            ->where(['order_id'=>$order_id,'kind'=>'refund'])
            ->value('transactions_id');
        if(!$refund_id){
            $refund_id    = Db::name('customer_refunds')
                ->where(['order_id'=>$order_id])
                ->value('refund_id');
        }

        $refund_status   =    0;
        if($refund_id){
            $refund_status  = 4;
        }

        $payment_info  = Db::name('order_transactions')
            ->field('id,amount,currency')
            ->where(['order_id'=>$order_id])
            ->order('id desc')
            ->find();
        
        // if(!$payment_info){
        //     return $this->jsonMessage(201, true, '暂无支付数据');
        // }
        $payment_info['amount'] = $payment_info['amount']??0;
        if($payment_info['amount'] == 0){
            $payment_info['amount'] = $order_info['total_price'] ?? 0;
        }
        $is_part = 0;
        if($refund_payment<$payment_info['amount']){
            $is_part =1;
        }

        //数据入库逻辑
        $info = [
            'SpecificReasons'    =>$SpecificReasons,
            'ReasonForRefund'    =>$ReasonForRefund,
            'ProductSku'         =>$ProductSku,
            'skus'               =>$skus,
            'Supplementary'      =>$Supplementary,
            'order_id'           =>$order_id,
            'order_number'       =>$order_number,
            'shop_id'            =>$shop_id,
            'refund_payment'     =>$refund_payment,
            'payment'            =>$payment_info['amount'],
            'currency'           =>$currency,
            'is_part'            =>$is_part,
            'refund_status'      =>$refund_status,
            'update_time'        =>date("Y-m-d H:i:s", time()),
            'create_time'        =>date("Y-m-d H:i:s", time()),
        ];
        $refundsHistory = Db::name('customer_refunds')
            ->where('order_id',$order_id)
            ->where('shop_id',$shop_id)
            ->find();
        if(!empty($refundsHistory)){
            if($refundsHistory['SpecificReasons'] == '补发'){
                return $this->jsonMessage(201, true, '已有补发记录',$refundsHistory);
            }
            if($refundsHistory['SpecificReasons'] == '确认退款'){
                return $this->jsonMessage(201, true, '已有退款记录',$refundsHistory);
            }else{
                //修改
                $res = Db::name('customer_refunds')->where('id',$refundsHistory['id'])->update($info);
            }
        }else{
            //新增
            $res = Db::name('customer_refunds')->insert($info);
        }
        return $this->jsonMessage(200, true, '操作成功',$res);
    }

    
    /**
     * @desc 同步到待退款列表
     * @author xx
     * @date 2025-03-01
     */
    public function RegistrationRefundedit($data=[]){
        $SpecificReasons = $data['SpecificReasons'] ?? "";
        $id = $data['id'] ?? 0;
        if(empty($SpecificReasons)){
            return $this->jsonMessage(201, true, '请添加退款意向');
        }
        if(empty($id)){
            return $this->jsonMessage(201, true, '网络错误，请刷新页面');
        }
        $shop_name = $data['shop_name'] ?? "";
        $shop_id = 0;
        switch ($shop_name) {
            case 'SheCurve':
                $shop_id = 17;
                break;
            case 'woobilly':
                $shop_id = 21;
                break;
            case 'LilyLove':
                $shop_id = 18;
                break;
            case 'kisslove':
                $shop_id = 22;
                break;
            default:
                $shop_id = 0;
        }
        if($shop_id == 0){
            return $this->jsonMessage(201, true, '请添加店铺');
        }
        if($SpecificReasons == '产品问题反馈' || $SpecificReasons == '补发'){
            $currency = $data['currency'] ?? "";
            $refund_payment = $data['amount'] ?? 0;
        }else{
            $currency = $data['currency'] ?? "";;
            if(empty($currency)){
                return $this->jsonMessage(201, true, '请添加币种');
            }
            $refund_payment = $data['amount'] ?? 0;
            if($refund_payment <= 0){
                return $this->jsonMessage(201, true, '请添加退款金额');
            }
        }
        $order_number = $data['order_number'] ?? "";
        //新增条件
        $ReasonForRefund = $data['ReasonForRefund'] ?? "";
        $ProductSku = $data['ProductSku'] ?? "";
        $Supplementary = $data['Supplementary'] ?? "";
        $valuesome = [21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44];
        $valuesome2 = [37,43,48];
        if(!empty($ReasonForRefund)){
            if(in_array($ReasonForRefund,$valuesome2)){
                 //其他产品质量问题
                if(empty($Supplementary)){
                    return $this->jsonMessage(201, true, '请先添加补充描述');
                }
            }
            if(in_array($ReasonForRefund,$valuesome)){
                //其他产品质量问题
                if(empty($ProductSku)){
                    return $this->jsonMessage(201, true, '请先添加SKU');
                }
            }
        }
        $skus = "";
        if(!empty($ProductSku)){
            $order_info = db::name('order_info')->field('sku')->where('id',"in",$ProductSku)->select()->toarray();
            $skus = array_column($order_info,'sku');
            $skus = implode(',',$skus);
            $skus = $skus ?? "";

            $ProductSku = implode(',',$ProductSku);
        }

        //同步到待退款列表
        $order_info      =    Db::name('order')->field('id,order_id,total_price')->where(['shop_id'=>$shop_id,'order_number'=>$order_number])->find();
        $order_id        =    $order_info['order_id']??'';
        if(!$order_id)  return $this->jsonMessage(201, true, '订单数据不匹配');

        //有Dispute标签的不同步
        $tags = Db::name('order_achievement')->where('order_id',$order_id)->value('tags');
        if(isset($tags) && strpos($tags,'dispute') !== false){
            // return $this->jsonMessage(201, true, '订单有dispute标签，不能同步到待退款列表');
        }

        //查看当前$order_id是否退过款;
        $refund_id       = Db::name('order_transactions')
            ->where(['order_id'=>$order_id,'kind'=>'refund'])
            ->value('transactions_id');
        if(!$refund_id){
            $refund_id    = Db::name('customer_refunds')
                ->where(['order_id'=>$order_id])
                ->value('refund_id');
        }

        $refund_status   =    0;
        if($refund_id){
            $refund_status  = 4;
        }

        $payment_info  = Db::name('order_transactions')
            ->field('id,amount,currency')
            ->where(['order_id'=>$order_id])
            ->order('id desc')
            ->find();
        
        // if(!$payment_info){
        //     return $this->jsonMessage(201, true, '暂无支付数据');
        // }
        $payment_info['amount'] = $payment_info['amount']??0;
        if($payment_info['amount'] == 0){
            $payment_info['amount'] = $order_info['total_price'] ?? 0;
        }
        $is_part = 0;
        if($refund_payment<$payment_info['amount']){
            $is_part =1;
        }

        //数据入库逻辑
        $info = [
            'SpecificReasons'    =>$SpecificReasons,
            'ReasonForRefund'    =>$ReasonForRefund,
            'ProductSku'         =>$ProductSku,
            'skus'               =>$skus,
            'Supplementary'      =>$Supplementary,
            'order_id'           =>$order_id,
            'order_number'       =>$order_number,
            'shop_id'            =>$shop_id,
            'refund_payment'     =>$refund_payment,
            'payment'            =>$payment_info['amount'],
            'currency'           =>$currency,
            'is_part'            =>$is_part,
            'refund_status'      =>$refund_status,
            'update_time'        =>date("Y-m-d H:i:s", time()),
            'create_time'        =>date("Y-m-d H:i:s", time()),
        ];
        $res = Db::name('customer_refunds')->where('id',$id)->update($info);

        return $this->jsonMessage(200, true, '操作成功',$res);
    }
    /**
     * @desc 同步到待退款详情
     * @author xx
     * @date 2025-03-01
     */
    public function RegistrationRefundinfo($data=[]){
        $email = $data['amp;email'] ?? "";
        if(empty($email)){
            $email = $data['email'] ?? "";
        }
        $slug = $data['slug'] ?? "";
        if(empty($slug)){
            $slug = $data['slug'] ?? "";
        }
        $brand = $data['brand'] ?? "";
        if($brand == 'shecurve' && !empty($email)){
            $order_id = Db::name('order_customer')
                ->where('email',$email)
                ->where('shop_id','17')
                ->value('order_id');
            if($order_id){
                $order_achievement = Db::name('order')->field('total_price,order_number')->where('order_id',$order_id)->find();
                $shop_name = 'SheCurve';
            }
        }
        if($brand == '4304ef' && !empty($email)){
            $order_id = Db::name('order_customer')
                ->where('email',$email)
                ->where('shop_id','21')
                ->value('order_id');
            if($order_id){
                $order_achievement = Db::name('order')->field('total_price,order_number')->where('order_id',$order_id)->find();
                $shop_name = 'woobilly';
            }
        }
        if($brand == 'lilylove' && !empty($email)){
            $order_id = Db::name('order_customer')
                ->where('email',$email)
                ->where('shop_id','18')
                ->value('order_id');
            if($order_id){
                $order_achievement = Db::name('order')->field('total_price,order_number')->where('order_id',$order_id)->find();
                $shop_name = 'LilyLove';
            }
        }
        if($brand == 'kisslove' && !empty($email)){
            $order_id = Db::name('order_customer')
                ->where('email',$email)
                ->where('shop_id','22')
                ->value('order_id');
            if($order_id){
                $order_achievement = Db::name('order')->field('total_price,order_number')->where('order_id',$order_id)->find();
                $shop_name = 'kisslove';
            }
        }
        $res = [
            'slug' => $slug ?? "",
            'shop_name' => $shop_name ?? "",
            'order_number' => $order_achievement['order_number'] ?? "",
        ];
        return $this->jsonMessage(200, true, '操作成功', $res);
    }



    //获取用户登录token
    public function getAccessToken($code) {
        $app_access_token      = (new FeiShuMessageLogic())->get_app_access_token();
        //获取用户token
        $basic_url             = Config('Logisticskey.fei_shu.basic_url');
        $user_access_token_url = Config('Logisticskey.fei_shu.app_user_token');
        $url                   = $basic_url.$user_access_token_url;
        $data                  = [
            'grant_type'    => 'authorization_code',
            'code'          =>  $code,
        ];
        $response =  HttpUtil::PostUrlShpf($url,$app_access_token,$data);
        $response =  json_decode($response, true);
        htmlLog(['code'=>$code,'response'=>$response],OPERATE_LOG . date('Ym') . '/getUserAccessToken/' . date('Ymd') . '.txt');
        return $response['data']['access_token']??'';
    }

     // 获取用户信息
     public function getUserInfo($accessToken) {
         $basic_url             = Config('Logisticskey.fei_shu.basic_url');
         $user_url              = Config('Logisticskey.fei_shu.app_user_info');
         $url                   = $basic_url.$user_url;
         $info                  = HttpUtil::getUrlStripe($url,['apikey'=>$accessToken]);
         $open_id               = $info['data']['open_id']??'';
         $user_name             = $info['data']['name']??'';
         htmlLog(['accessToken'=>$accessToken,'info'=>$info],OPERATE_LOG . date('Ym') . '/getUserInfo/' . date('Ymd') . '.txt');
         $admin_arr             = ['ou_f7192fb282ef3b6cbb04ec48bb1f803a','ou_2b15556877ac377beaf95c470f6355a4','ou_d9c21a37be5e19bf277e48d765f2da3d'];
         //查看用户的信息;
         if(in_array($open_id,$admin_arr)){
             $user_info = Db::name('system_admin')->where(['open_id'=>$open_id])->find();
         }else{
             $user_info = Db::name('system_admin')->where(['username'=>$user_name])->find();
         }
         if(!$user_info['open_id']){
             //更新open_id
             Db::name('system_admin')->where(['id'=>$user_info['id']])->update(
                 [
                     'open_id'=>$open_id,
                 ]
             );
         }
         return $user_info['phone']??'';
    }

}